package com.oocl.scp_ssh.controller.impl;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

import com.oocl.scp_ssh.controller.Controller;
import com.oocl.scp_ssh.pojo.impl.ScpMsg;
import com.oocl.scp_ssh.util.FileUtils;

public class ScpController implements Controller{


	private final String PATH = "upload";

	private ScpMsg msg;
	
	public ScpController(ScpMsg msg) {
		super();
		this.msg = msg;
	}
	
	@Override
	public void dealWithClient(InputStream in, OutputStream out) throws IOException {
		BufferedReader reader = new BufferedReader(new InputStreamReader(in));
		
		if(msg!=null) {
			String targetPath = PATH+msg.getRemoteFilePath();
			File target = new File(targetPath);
			if(target.isDirectory()) {
				targetPath+=msg.getLocalFilePath().substring(msg.getLocalFilePath().lastIndexOf("/")+1, msg.getLocalFilePath().length());
			}
			System.out.println("这时候，文件上传地址为："+ targetPath);
			FileUtils.createFile(targetPath);
			File targetFile = new File(targetPath);
			
			///告诉客户端，可以传数据了
			out.write(("200ok\n").getBytes());
			
			String fileLine = reader.readLine();
			System.out.println("从Client传来： "+fileLine);
			String fileSize = fileLine.split(":")[1];
			long fullSize = Long.valueOf(fileSize);
			long curPos  = 0;
			
			///告诉客户端，可以传数据了
			out.write(("200ok\n").getBytes());
			
			///开始准备接收数据
			OutputStream fout = new FileOutputStream(targetFile);
			int flen = 0;
			byte[] buf = new byte[1024];
			boolean isFinished = false;
			while(!isFinished) {
				if((curPos + buf.length)>fullSize){
					flen = in.read(buf, 0, (int) (fullSize-curPos));
					isFinished = true;
				}else{
					flen = in.read(buf);
					curPos+= flen;
				}
				fout.write(buf, 0, flen);
			}
			fout.close();
			
			out.write(("success!\n").getBytes());
			
			
//			if(socket.isClosed())
//			System.out.println("Server: socket is closed!");
		}else {
			out.write(("Server: Please send me the right command.").getBytes());
		}
	}

}
